package com.rrd.itext.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rrd.itext.utils.GlobalNames;
import com.rrd.itext.utils.IOUtil;
import com.rrd.itext.utils.PDFBuilder;
import com.rrd.itext.xmlHandler.PDFLayoutHandler;

/**
 * Servlet implementation class SamplePDF
 */
public class SamplePDF extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SamplePDF() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        //Get the template name
        String templateName = (String) request.getAttribute("templateName");
        if (templateName == null || "".equals(templateName)) {
            templateName = request.getParameter("templateName");
        }
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        String webRootPath = request.getSession().getServletContext().getRealPath("\\");
        String templatePath = webRootPath + "resources\\";
        if (templateName != null && !"".equals(templateName)) {
            templatePath = templatePath + templateName + "\\";
        }
        String dataXML = request.getParameter("dataXML");
        if (dataXML == null) {
            dataXML = (String) request.getAttribute("dataXmlFile");
        }
        //Get image path
        String imagePath = (String) request.getAttribute("imagePath");
        if (imagePath == null) {
            imagePath = webRootPath + "images\\";
        }
        PDFBuilder builder = new PDFBuilder(imagePath);
        
        PDFLayoutHandler handler = new PDFLayoutHandler(templatePath, dataXML);
        response.reset();
        ServletOutputStream responseOutputStream = response.getOutputStream();
        try{
            handler.handleMessage(builder, pdfOutputStream);
        }catch(Exception e){
            e.printStackTrace();
            responseOutputStream.write(e.getMessage().getBytes());
            responseOutputStream.flush();
            responseOutputStream.close();
            return;
        }
        
        //response.setHeader("Expires", "0");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + GlobalNames.PDF_FILE_NAME + "\"");
        response.setContentLength(pdfOutputStream.size());
        
        // Write the PDF
        responseOutputStream.write(pdfOutputStream.toByteArray());
        responseOutputStream.flush();
        responseOutputStream.close();
//        if (imagePath.indexOf("images") > 0) {
//            try {
//                this.del(imagePath);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }
    
    private void del(String filepath) {
        File f = new File(filepath);
        if (f.exists() && f.isDirectory()) {
            if (f.listFiles().length == 0) {
                f.delete();
            } else {
                File delFile[] = f.listFiles();
                int i = f.listFiles().length;
                for (int j = 0; j < i; j++) {
                    if (delFile[j].isDirectory()) {
                        del(delFile[j].getAbsolutePath());
                    }
                    delFile[j].delete();
                }
            }
        }
    }
}
